package playground.fibu.ejb.dao.mysql;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

import playground.fibu.ejb.dao.BookingDAO;
import playground.fibu.ejb.dao.FibuDAOException;
import playground.fibu.ejb.entity.Booking;

public class MySQLBookingDAO implements BookingDAO {

	private static final String PERSISTENCE_UNIT_NAME = "fibu";
	private static EntityManagerFactory factory;

	public MySQLBookingDAO() {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	}

	@Override
	public void save(Booking booking) throws FibuDAOException {
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		em.persist(booking);		
		em.getTransaction().commit();
		em.close();
	}

	@Override
	public void delete(Booking booking) throws FibuDAOException {
		

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Booking> findAll() throws FibuDAOException {
		EntityManager em = factory.createEntityManager();
		Query query = em.createQuery("select b from Booking b");
		try {
			return (List<Booking>) query.getResultList();
			
		} catch (NoResultException e) {
			throw new FibuDAOException(e);
		}
	}

	@Override
	public Booking findByPrimaryKey(long id) throws NoResultException{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Booking> findByDate(Date date) throws NoResultException {
		// TODO Auto-generated method stub
		return null;
	}

}
